package com.example.diary

import DiaryDbHelper
import android.os.Bundle
import android.view.*
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.R
import com.example.adapter.DiaryRecyclerAdapter
import com.example.model.Diary

class DiaryListFragment : Fragment() {
    private val diaryList = ArrayList<Diary>()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_diary_list, container, false)
    }

    override fun onResume() {
        super.onResume()
        diaryList.clear()
        val diaryRecyclerView: RecyclerView? = view?.findViewById(R.id.diaryRecyclerView)
        val layoutManager = LinearLayoutManager(activity)

        // 从数据库中读取数据
        val dbHelper = DiaryDbHelper(this.context, "diary.db", 1)
        val db = dbHelper.writableDatabase
        // 添加初始数据（测试用）
//        val values = ContentValues().apply {
//            put("title", "测试标题")
//            put("description", "内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容v")
//        }
//        db.insert("diary", null, values)

        val cursor = db.rawQuery("select * from diary order by id DESC", null)
        if (cursor.moveToFirst()) {
            do {
                val id = cursor.getInt(cursor.getColumnIndexOrThrow("id"))
                val title = cursor.getString(cursor.getColumnIndexOrThrow("title"))
                val description = cursor.getString(cursor.getColumnIndexOrThrow("description"))
                diaryList.add(Diary(id, title, description))
            } while (cursor.moveToNext())
        }

        // 展示日记
        diaryRecyclerView?.layoutManager = layoutManager
        val diaryRecyclerAdapter = DiaryRecyclerAdapter(activity, diaryList)
        diaryRecyclerView?.adapter = diaryRecyclerAdapter
    }


}